package org.example.tx.acl;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AclInitializer implements InitializingBean {

    @Resource(name = "jdbcTemplate2")
    private JdbcTemplate jdbcTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        jdbcTemplate.execute("create table if not exists `acl` (" +
                "    `id` int not null auto_increment primary key," +
                "    `oid` int not null," +
                "    `version` int not null" +
                ")");

        jdbcTemplate.execute("create table if not exists `ace` (" +
                "    `id` int not null auto_increment primary key," +
                "    `aclId` int not null," +
                "    `sid` int not null," +
                "    `permissions` int not null," +
                "    `version` int not null," +
                "    `seq` int not null" +
                ")");

        String insertAclSql = "replace into `acl` (`id`, `oid`, `version`) values (?, ?, ?)";
        jdbcTemplate.batchUpdate(insertAclSql, List.of(
                new Object[]{1, 1, 0},
                new Object[]{2, 2, 0},
                new Object[]{3, 3, 0}
        ));

        String insertAceSql = "replace into `ace` (`id`, `aclId`, `sid`, `permissions`, `version`, `seq`) values (?, ?, ?, ?, ?, ?)";
        jdbcTemplate.batchUpdate(insertAceSql, List.of(
                new Object[]{1, 1, 1001, 0xff, 0, 1},
                new Object[]{2, 1, 1002, 0xff, 0, 2},
                new Object[]{3, 1, 1003, 0xff, 0, 3}
        ));
    }
}
